package com.byusi.zhq;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;

public class ZhqConverter {

    public static void main(String[] args) {
        if (args.length == 0 || (args.length != 3 && !args[0].equals("-byusi"))) {
            printUsage();
            return;
        }

        if (args[0].equals("-byusi")) {
            showEasterEgg();
            return;
        }

        try {
            processConversion(args);
            System.out.println("文件已成功输出到: " + args[2]);
        } catch (IOException | IllegalArgumentException e) {
            System.err.println("操作失败: " + e.getMessage());
        }
    }

    private static void processConversion(String[] args) throws IOException {
        String mode = args[0];
        String sourceFile = args[1];
        String outputFile = args[2];

        if (mode.equals("-z")) {
            convertToBinary(sourceFile, outputFile);
        } else if (mode.equals("-z16")) {
            convertToHex(sourceFile, outputFile);
        } else if (mode.equals("-h")) {
            convertFromBinary(sourceFile, outputFile);
        } else if (mode.equals("-h16")) {
            convertFromHex(sourceFile, outputFile);
        } else {
            throw new IllegalArgumentException("无效的参数: " + mode);
        }
    }

    private static void printUsage() {
        System.out.println(centerText("ByUsi 文件转换工具 v1.3.2"));
        System.out.println("\n使用方法:");
        System.out.println("  转换为二进制     : zhq -z 源文件 输出文件");
        System.out.println("  转换为十六进制   : zhq -z16 源文件 输出文件");
        System.out.println("  从二进制还原文件 : zhq -h 源文件 输出文件");
        System.out.println("  从十六进制还原   : zhq -h16 源文件 输出文件");
        System.out.println("  彩蛋模式        : zhq -byusi");
    }

    private static void convertToBinary(String sourceFile, String outputFile) throws IOException {
        try (InputStream is = Files.newInputStream(Paths.get(sourceFile));
             PrintWriter pw = new PrintWriter(outputFile)) {
            
            StringBuilder buffer = new StringBuilder();
            int byteData;
            
            while ((byteData = is.read()) != -1) {
                buffer.append(String.format("%8s", Integer.toBinaryString(byteData))
                        .replace(' ', '0'))
                        .append(" ");
            }
            
            pw.print(buffer.toString().trim());
        }
    }

    private static void convertToHex(String sourceFile, String outputFile) throws IOException {
        try (InputStream is = Files.newInputStream(Paths.get(sourceFile));
             PrintWriter pw = new PrintWriter(outputFile)) {
            
            StringBuilder buffer = new StringBuilder();
            int byteData;
            
            while ((byteData = is.read()) != -1) {
                buffer.append(String.format("%02X", byteData)).append(" ");
            }
            
            pw.print(buffer.toString().trim());
        }
    }

    private static void convertFromBinary(String sourceFile, String outputFile) throws IOException {
        String content = Files.readString(Paths.get(sourceFile));
        String[] binaryChunks = content.split(" ");
        
        try (OutputStream os = Files.newOutputStream(Paths.get(outputFile))) {
            for (String chunk : binaryChunks) {
                os.write(Integer.parseInt(chunk, 2));
            }
        }
    }

    private static void convertFromHex(String sourceFile, String outputFile) throws IOException {
        String content = Files.readString(Paths.get(sourceFile));
        String[] hexChunks = content.split(" ");
        
        try (OutputStream os = Files.newOutputStream(Paths.get(outputFile))) {
            for (String chunk : hexChunks) {
                os.write(Integer.parseInt(chunk, 16));
            }
        }
    }

    private static void showEasterEgg() {
        Scanner scanner = new Scanner(System.in);
        System.out.println(centerText("当前版本: 1.3.2"));
        System.out.println(centerText("更新日志: 增强大文件处理性能"));
        System.out.print("\n请输入您的名字: ");
        String name = scanner.nextLine();
        System.out.println("\n" + centerText("欢迎您，" + name));
        System.out.println(centerText("访问官网: https://byusi.cn"));
        System.out.println(centerText("感谢使用本工具！"));
    }

    private static String centerText(String text) {
        int terminalWidth = 80;
        if (text.length() >= terminalWidth) return text;
        int padding = (terminalWidth - text.length()) / 2;
        return " ".repeat(padding) + text;
    }
}
